// TetrisView.h : interface of the CTetrisView class
//
/////////////////////////////////////////////////////////////////////////////

#pragma once

#include "TetrisApp.h"

class CTetrisView : public CWindowImpl<CTetrisView>
{
public:
	CTetrisApp *m_pTetrisApp;

public:
	DECLARE_WND_CLASS(NULL)

	BOOL PreTranslateMessage(MSG* pMsg)
	{
		pMsg;
		return FALSE;
	}

	BEGIN_MSG_MAP(CTetrisView)
		MESSAGE_HANDLER(WM_CREATE, OnCreate)
		MESSAGE_HANDLER(WM_PAINT, OnPaint)
		MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
		MESSAGE_HANDLER(WM_KEYDOWN, OnKeydown)
		MESSAGE_HANDLER(WM_TIMER, OnTimer)
	END_MSG_MAP()

	LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		::PlaySound(
			MAKEINTRESOURCE(IDR_WAVE_IDLE),
			::GetModuleHandle(NULL),
			SND_ASYNC | SND_RESOURCE | SND_LOOP
		);
		m_pTetrisApp = NULL;
		return 0;
	}

	LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		CPaintDC dc(m_hWnd);

		//TODO: Add your drawing code here
		if (m_pTetrisApp != NULL) {
			m_pTetrisApp->Paint();
		}

		return 0;
	}

	LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		CRect rect;
		GetClientRect(&rect);

		CBrush brush;
		brush.CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));
		
		::FillRect((HDC)wParam, &rect, brush);

		return 0;
	}

	LRESULT OnKeydown(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		if (m_pTetrisApp != NULL) {
			switch (wParam) {
			case VK_SPACE:
				m_pTetrisApp->OnKeydown(VK_SPACE);
				break;

			case VK_UP:
				m_pTetrisApp->OnKeydown(VK_UP);
				break;

			case VK_DOWN:
				m_pTetrisApp->OnKeydown(VK_DOWN);
				break;

			case VK_LEFT:
				m_pTetrisApp->OnKeydown(VK_LEFT);
				break;

			case VK_RIGHT:
				m_pTetrisApp->OnKeydown(VK_RIGHT);
				break;
			}
		}

		return 0;
	}

	LRESULT OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		switch (wParam) {
		case CTetrisApp::ID_TETRIS_APP:
			m_pTetrisApp->OnTimer();
			break;

		default:
			break;
		}

		return 0;
	}

	void StartApp(const CRect &clientRect)
	{
		Rect rect(clientRect.left, clientRect.top, clientRect.Width(), clientRect.Height());
		m_pTetrisApp = new CTetrisApp(*this, rect);
		m_pTetrisApp->Start();
	}
};
